package com.syqc.monitor.ui.alarm

import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gyf.immersionbar.ktx.immersionBar
import com.syqc.comlib.base.BaseActivity
import com.syqc.comlib.custom.MLoadingDialog
import com.syqc.comlib.databinding.IncludeRecyclerMathBinding
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.ScreenUtil
import com.syqc.comlib.utils.loadGif
import com.syqc.comlib.utils.startActivityTo
import com.syqc.custom.LeftRightTextView
import com.syqc.entity.AlarmDetail
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityHandleInfoBinding
import com.syqc.monitor.ui.realalarm.MediaInfoActivity
import com.syqc.utils.Keys
import com.syqc.utils.ToolsUtil
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

/**
 *@Author Jasper
 *@Time   2020/12/1
 *@Desc   报警类型列表
 */
class HandleAlarmInfoActivity :
    BaseActivity<ActivityHandleInfoBinding>(ActivityHandleInfoBinding::inflate) {
    private var mEntity: AlarmDetail? = null
    private lateinit var alarmId: String
    private var carId: String? = null
    private lateinit var typeName: String
    private var isAllChoose: Boolean = false
    private var isCar = false
    private lateinit var mRecyclerVB: IncludeRecyclerMathBinding

    private val mAdapter by lazy { MAdapter(isCar) }
    private val mViewModel by viewModels<HandleAlarmVM>()

    private val mPhrasePopup by lazy { AlarmTextPopup(this) }

    //是否多选处理
    private var isAllDialog = false

    private val dialog by lazy {
        AlarmHandlePopup(false, this, textBack = {
            isAllDialog = false
            if (mViewModel.mAlarmNote == null || mViewModel.isNote404) {
                mViewModel.getAlarmNote()
            } else {
                mPhrasePopup.showAtLocation(window.decorView, mViewModel.mAlarmNote!!)
            }

        }, callback = {
            mEntity?.run {
                mViewModel.processAlarm(carId, alarmType, time, it)
            }
        })
    }

    private val allDialog by lazy {
        AlarmHandlePopup(true, this, textBack = {
            isAllDialog = true
            if (mViewModel.mAlarmNote == null || mViewModel.isNote404) {
                mViewModel.getAlarmNote()
            } else {
                mPhrasePopup.showAtLocation(window.decorView, mViewModel.mAlarmNote!!)
            }

        }, callback = {
            mViewModel.handleAll(it)
        })
    }


    private val emptyView by lazy {
        val view =
            layoutInflater.inflate(R.layout.layout_empty_view, mRecyclerVB.recyclerView, false)
        view.findViewById<ImageView>(R.id.ivNoData).loadGif(this, R.mipmap.ic_empty)
        view
    }

    override fun initView() {
        MLoadingDialog.clear()
        immersionBar { titleBar(binding.flToolbar) }
        isCar = intent.getBooleanExtra(Keys.INTENT_OTHER, false)
        carId = intent.getStringExtra(Keys.INTENT_CAR_ID)
        mViewModel.isCar = isCar
        initViewModel()
        if (isCar) {
            typeName = intent.getStringExtra(Keys.INTENT_TITLE) ?: ""
            val alarmNum = intent.getStringExtra(Keys.INTENT_TEAM_NUM) ?: ""
            binding.tvTitle.text = "$typeName($alarmNum)"
            binding.editSearch.setHint(R.string.desc_input_alarm_type)
            mViewModel.getAlarmDetailCar(carId!!)
        } else {
            typeName = intent.getStringExtra(Keys.INTENT_TITLE) ?: ""
            val alarmNum = intent.getStringExtra(Keys.INTENT_TEAM_NUM) ?: ""
            alarmId = intent.getStringExtra(Keys.INTENT_ALARM_ID) ?: ""
            binding.tvTitle.text = "$typeName($alarmNum)"
            if (alarmId.isEmpty()) return
            mViewModel.getAlarmByType(alarmId)
        }

        mRecyclerVB = IncludeRecyclerMathBinding.bind(binding.root)
        mRecyclerVB.recyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerVB.recyclerView.setPadding(0, ScreenUtil.dp2px(this, 12), 0, 0)
        mRecyclerVB.recyclerView.adapter = mAdapter


    }

    private fun initViewModel() {
        mViewModel.noteLive.observe(this) {
            if (it != null) {
                mPhrasePopup.showAtLocation(window.decorView, mViewModel.mAlarmNote!!)
            }
        }

        mViewModel.toastObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe {
                toastObserver(it)
            }

        mViewModel.alarms.observe(this) {
            binding.llAllChoose.isVisible = isAllChoose && it.size != 0
            binding.tvAction.isVisible = it.size != 0
            binding.tvTitle.text = "$typeName(${it.size})"
            if (it.isNullOrEmpty()) {
                mAdapter.setEmptyView(emptyView)
            }
            mAdapter.setList(it)
            binding.tvAlarmAllUnCheck.isSelected = mViewModel.isNoChoose()
            binding.tvAlarmAllCheck.isSelected = mViewModel.isAllChoose()
        }


        mViewModel.handle.observe(this) {
            if (it) {
                dialog.dismiss()
                binding.editSearch.setText("")
                if (isCar) {
                    if (carId.isNullOrEmpty()) return@observe
                    mViewModel.getAlarmDetailCar(carId!!)
                } else {
                    if (alarmId.isEmpty()) return@observe
                    mViewModel.getAlarmByType(alarmId)
                }
            }
        }

        mViewModel.handleAll.observe(this) {
            if (it) {
                allDialog.dismiss()
                binding.editSearch.setText("")
                if (isCar) {
                    if (carId.isNullOrEmpty()) return@observe
                    mViewModel.getAlarmDetailCar(carId!!)
                } else {
                    if (alarmId.isEmpty()) return@observe
                    mViewModel.getAlarmByType(alarmId)
                }
            }
        }

        mViewModel.start.observe(this) {
            startActivityTo<MediaInfoActivity>(this) {
                putExtra(Keys.INTENT_TITLE, mViewModel.plate)
                putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                putParcelableArrayListExtra(Keys.INTENT_DATA, it)
            }
        }
    }

    override fun setListener() {
        binding.ivBack.filterFast {
            finish()
        }

        binding.tvAction.filterFast {
            if (mAdapter.data.size <= 0) return@filterFast
            isAllChoose = !isAllChoose
            binding.tvAction.isSelected = isAllChoose
            binding.llAllChoose.isVisible = isAllChoose
            mAdapter.isAllChoose = isAllChoose
            mAdapter.notifyDataSetChanged()
        }

        binding.tvAlarmAllCheck.filterFast {
            mViewModel.chooseAll(true)
            binding.tvAlarmAllCheck.isSelected = true
            binding.tvAlarmAllUnCheck.isSelected = false
        }

        binding.tvAlarmAllUnCheck.filterFast {
            mViewModel.chooseAll(false)
            binding.tvAlarmAllCheck.isSelected = false
            binding.tvAlarmAllUnCheck.isSelected = true
        }

        binding.tvHandleAll.filterFast {
            if (!mViewModel.hasChoose()) return@filterFast
            if (!allDialog.isShowing && !isFinishing) allDialog.showAtLocation(window.decorView)
            allDialog.setData(typeName)
        }


        binding.ivClear.setOnClickListener {
            binding.editSearch.setText("")
        }

        binding.editSearch.doAfterChanged {
            mViewModel.search(it)
            binding.ivClear.isVisible = !it.isNullOrEmpty()
        }

        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ivInfo -> {
                    if (ToolsUtil.isFastClick()) return@setOnItemChildClickListener
                    val mEntity = mAdapter.data[position]
                    mViewModel.carId = mEntity.carId
                    mViewModel.plate = mEntity.carPlate
                    mViewModel.getAlarmInfo(mEntity.time, mEntity.alarmType)
                    return@setOnItemChildClickListener
                }

                R.id.ivChoose -> {
                    val mEntity = mAdapter.data[position]
                    mEntity.isChoose = !mEntity.isChoose
                    mAdapter.notifyItemChanged(position)
                    binding.tvAlarmAllUnCheck.isSelected = mViewModel.isNoChoose()
                    binding.tvAlarmAllCheck.isSelected = mViewModel.isAllChoose()
                }

                else -> {
                    if (ToolsUtil.isFastClick()) return@setOnItemChildClickListener
                    mEntity = mAdapter.data[position]
                    if (!dialog.isShowing && !isFinishing) dialog.showAtLocation(window.decorView)
                    dialog.setData(mEntity!!.alarmName, mEntity!!.carPlate)
                }
            }
        }

        mPhrasePopup.setOnCallback(object : AlarmTextPopup.OnCallback {
            override fun callback(desc: String) {
                if (isAllDialog) allDialog.setHandText(desc) else dialog.setHandText(desc)
            }

        })
    }

    override fun onDestroy() {
        super.onDestroy()
        if (dialog.isShowing) dialog.dismiss()
        if (allDialog.isShowing) allDialog.dismiss()
    }
}

class MAdapter(private val isCar: Boolean) :
    BaseQuickAdapter<AlarmDetail, BaseViewHolder>(R.layout.item_alarm_headle_info) {
    //是否显示选中
    var isAllChoose = false

    init {
        addChildClickViewIds(R.id.tvHandle, R.id.ivInfo, R.id.ivChoose)
    }

    override fun convert(holder: BaseViewHolder, item: AlarmDetail) {
        item.run {
            if (isCar) {
                holder.setText(R.id.tv_alarm_info_car, alarmName)
                holder.setGone(R.id.lr_tv_car_name, true)
            } else {
                holder.setText(R.id.tv_alarm_info_car, carPlate)
                holder.setGone(R.id.lr_tv_car_name, false)
            }
            holder.getView<LeftRightTextView>(R.id.lr_tv_car_name)
                .setRightText(carName)

            holder
                .setText(R.id.tv_alarm_info_address, addr)
            holder.getView<LeftRightTextView>(R.id.lr_tv_alarm_belong)
                .setRightText(teamName ?: "")
            holder.getView<LeftRightTextView>(R.id.lr_tv_alarm_info_time)
                .setRightText(time)
            holder.getView<LeftRightTextView>(R.id.lr_tv_alarm_info_speed)
                .setRightText("$speed ${context.getString(R.string.unit_speed)}")
            holder.setVisible(R.id.ivInfo, !fjNum.isNullOrEmpty() && fjNum.toInt() > 0)
            val tvHandle = holder.getView<TextView>(R.id.tvHandle)
            tvHandle.isVisible = !isAllChoose
            val chooseView = holder.getView<ImageView>(R.id.ivChoose)
            chooseView.isSelected = isChoose
            chooseView.isVisible = isAllChoose
        }
    }
}
